<template>
    <UserNav/>
    <!-- 整体框架 -->
    <div style="margin-top: 80px">
        <!--全局导航栏-->
        <!-- 搜索区域开始：从主页拿到数据，反显至此页面，并通过拿过来的数据进行全局搜索 -->
        <div style="height: 100px; display: flex; align-items: center; justify-content: center; margin: 0 auto">
            <el-input :prefix-icon="Search" placeholder="请输入要搜索的内容"
                      v-model="searchQuery"
                      clearable
                      style="width: 360px; margin: 0 10px; height: 42px; font-size: 16px; font-weight: 500; border-radius: 50%"
                      size="large"
            />
            <el-button type="primary" @click="executeSearch" size="large">搜索</el-button>
        </div>
        <!--搜索区域结束-->

        <!-- 搜索结果展示区域开始 -->
        <div style="display: flex; align-items: center; justify-content: center">

            <!-- 结果展示开始 -->
<!--            <el-tabs v-model="activeTab" style="background-color: #fffefb; width: 1024px; min-height: 450px">-->
<!--                <el-tab-pane label="全 部" name="all">-->
<!--                    <div v-if="true" class="autobox-container-ar" style="display: flex; align-items: center; justify-content: center; margin-top: 40px" >-->
<!--                        <img src="@/assets/imge/暂无数据.jpg" alt="暂无数据" style="width: 260px; height: 260px">-->
<!--                    </div>-->
<!--                </el-tab-pane>-->
<!--                <el-tab-pane label="内 容" name="content">-->
<!--                    <div v-if="true" class="autobox-container-ar" style="display: flex; align-items: center; justify-content: center; margin-top: 40px" >-->
<!--                        <img src="@/assets/imge/暂无数据.jpg" alt="暂无数据" style="width: 260px; height: 260px">-->
<!--                    </div>-->
<!--                </el-tab-pane>-->
<!--                <el-tab-pane label="项 目" name="project">-->
<!--                    <div v-if="true" class="autobox-container-ar" style="display: flex; align-items: center; justify-content: center; margin-top: 40px" >-->
<!--                        <img src="@/assets/imge/暂无数据.jpg" alt="暂无数据" style="width: 260px; height: 260px">-->
<!--                    </div>-->
<!--                </el-tab-pane>-->
<!--                <el-tab-pane label="用 户" name="user">-->
<!--                    <div v-if="true" class="autobox-container-ar" style="display: flex; align-items: center; justify-content: center; margin-top: 40px" >-->
<!--                        <img src="@/assets/imge/暂无数据.jpg" alt="暂无数据" style="width: 260px; height: 260px">-->
<!--                    </div>-->
<!--                </el-tab-pane>-->
<!--            </el-tabs>-->
                <div style="width: 1024px; background-color: #fffefb; min-height: 450px; border-radius: 20px">
                    <div v-if="isNoData" class="autobox-container-ar" style="display: flex; align-items: center; justify-content: center; margin-top: 80px" >
                        <img src="@/assets/imge/暂无数据.jpg" alt="暂无数据" style="width: 260px; height: 260px">
                    </div>
                    <div v-else class="autobox-container-ar">
                        <!--博客列表开始-->
                        <div class="blog-list">
                            <!-- 卡片 -->
                            <div class="blog-item" v-for="item in searchResults" :key="item.contentId">
                                <router-link :to="`/contentdetail/${item.contentType}/${item.contentId}`">
                                    <!-- 内容主体区域 -->
                                    <div class="blog-main-content">

                                        <div style="display: flex; align-items: center; justify-content: space-between">
                                            <!-- 标题 + 内容（左） -->
                                            <div :style="item.cover ? 'width: 750px' : 'width: 920px'" >
                                                <strong class="blog-title" v-html="highlightText(item.title, searchQuery)"></strong>
                                                <div v-if="item.contentType !== 'QUESTION'" class="blog-desc" v-html="highlightText(truncateText(stripHtml(item.content), 150), searchQuery)"></div><!-- DOMPurify 库去除HTML标签 -->
                                            </div>
                                            <!-- 封面图片（右） -->
                                            <div class="blog-cover" v-if="item.cover">
                                                <el-image style="width: 100%; height: 100%; border-radius: 0.375rem" :src="item.cover" fit="cover" :preview-src-list="[item.cover]"/>
                                            </div>
                                        </div>
                                        <!-- 文章信息区域（预留）：置于内容底部靠左-->
                                        <div class="user-info-area">
                                            <!-- 用户信息区域 靠左 -->
                                            <el-avatar :src="item.user.profile_photo_path" shape="circle" :size="30" @error="errorHandler">
                                                <img
                                                    src="https://cube.elemecdn.com/e/fd/0fc7d20532fdaf769a25683617711png.png"
                                                    alt="加载错误"/> <!--图片加载失败的回退行为-->
                                            </el-avatar>
                                            <div class="interaction-info">
                                                <span>{{ item.user.username }}</span>
                                                <span class="icon-item"><img src="@/assets/icon_svg/浏览量.svg" alt="icon" style="width: 20px; height: 20px">{{ item.views }}</span>
                                                <span class="icon-item"><img src="@/assets/icon_svg/赞.svg" alt="点赞图标" style="width: 20px; height: 20px">{{ item.likes }}</span>
                                                <span class="icon-item"><img src="@/assets/icon_svg/_收藏.svg" alt="icon" style="width: 20px; height: 20px"> {{ item.collections }}</span>
                                            </div>
                                            <!--分类标签区域 靠右-->
                                            <div class="blog-meta">
                                                <span v-if="item.category?.categoryName" class="category-tag"><el-tag type="info">{{ item.category?.categoryName }}</el-tag></span>
                                                <span v-if="item.tags" class="tag-list"><el-tag v-for="tag in item.tags.split(',')" :key="tag" type="success">{{ tag }}</el-tag></span>
                                                <span class="publish-time">{{ item.created_at.split(' ')[0] }}</span>
                                            </div>
                                        </div>
                                    </div>
                                </router-link>
                            </div>
                        </div>
                        <!--内容列表结束-->
                    </div>
                </div>
            <!-- 结果展示结束 -->
        </div>
        <!-- 搜索结果展示区域结束 -->
    </div>
</template>

<script setup>

import UserNav from "@/components/UserNav.vue";
import { ref, onMounted,  } from 'vue'
import {Search} from "@element-plus/icons-vue";
import {ElMessage} from "element-plus";
import {useRoute, useRouter} from "vue-router";
import request from "@/utils/request.js";
import DOMPurify from "dompurify";

const errorHandler = () => true // 图片处理失败的回退行为
const isNoData = ref(false)

const route = useRoute()
const router = useRouter()
const searchQuery = ref('')
const searchResults = ref([])

// 页面加载时获取路由参数并设置搜索框值
onMounted(() => {
    if (route.query.q) {
        searchQuery.value = route.query.q
        // 如果有搜索参数，自动执行搜索
        executeSearch()
    } else {
        isNoData.value = true
    }
})

// 执行搜索的方法
const executeSearch = async () => {
    if (!searchQuery.value.trim()) {
        return
    }
    try {
        // 调用API进行搜索
        await request.get('/api/content/search', {
            params: {
                query: searchQuery.value,
            }
        }).then(res => {
            if (res.code === '200') {
                searchResults.value = res.data
                isNoData.value = searchResults.value.length === 0
            } else {
                searchResults.value = []
                isNoData.value = true
                ElMessage.error('搜索失败，请重试')
            }
        })
    } catch (error) {
        searchResults.value = []
        ElMessage.error('网络错误，请重试')
    }
}
// 安全地移除HTML标签并提取纯文本
const stripHtml = (html) => {
    if (!html) return '';

    // 使用DOMPurify清理HTML，防止XSS攻击
    const clean = DOMPurify.sanitize(html);

    // 创建临时元素提取文本内容
    const temp = document.createElement('div');
    temp.innerHTML = clean;

    // 获取纯文本内容并去除多余空格
    return (temp.textContent || temp.innerText || '').trim();
};

// 截断文本并添加省略号
const truncateText = (text, length) => {
    if (text.length <= length) return text;

    // 找到最后一个完整的单词
    let truncated = text.substring(0, length);
    let lastSpace = truncated.lastIndexOf(' ');

    // 如果找到了空格，在空格处截断以避免单词被截断
    if (lastSpace !== -1) {
        truncated = truncated.substring(0, lastSpace);
    }

    return truncated + '...';
};
// 高亮显示
const highlightText = (text, query) => {
    if (!query || !text) return text;

    // 使用正则表达式匹配查询词，不区分大小写
    const regex = new RegExp(query, 'gi');
    return text.replace(regex, match => `<span style="color: #1d7dfa">${match}</span>`);
};
</script>

<style scoped>
::v-deep .el-tabs__header {
    text-align: center;
}
::v-deep .el-tabs__item {
    min-width: 100px;
    text-align: center;
}

/*中间内容区域容器：*/
.autobox-container-ar {
    position: absolute;
    width: 1024px;
    box-sizing: border-box;
    background-color: #fffefb;
}

/*卡片样式*/
.blog-item {
    display: flex;
    flex-direction: row;
    align-items: flex-start;
    gap: 22px;
    padding: 20px;
    border-bottom: 2px #f5f4f1 solid;
    transition: transform 0.3s, box-shadow 0.3s;
}
.blog-item:hover {
    background-color: #f5f4f1;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.10); /* 轻微外阴影 */
}
/* 用户信息区域样式 */
.user-info-area {
    width: 100%;
    display: flex;
    align-items: center;
}

/* 内容主体区域样式 */
.blog-main-content {
    display: flex;
    flex-direction: column;
}

/*标题样式*/
.blog-title {
    font-size: 18px;
    font-weight: 600;
    color: #1a1a1a;
    margin: 10px 0 20px 0;
}
/*内容样式*/
.blog-desc {
    font-size: 14px;
    line-height: 1.6;
    color: #4f4f4f;
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-box-orient: vertical;
    -webkit-line-clamp: 3; /* 限制3行 */
    /*padding: 10px 0;*/
}

/* 封面图片样式 */
.blog-cover {
    flex: 0 0 180px; /* 固定宽度，不随内容缩放 */
    display: flex;
    align-items: center;
    width: 140px;
    height: 70px;
    position: absolute;
    right: 10px;
}

/*分类标签样式*/
.blog-meta {
    position: absolute;
    right: 10px;
    display: flex;
    align-items: center;
    gap: 10px;
    font-size: 14px;
    color: #666;
    margin-left: 10px;
}

/*互动信息区样式*/
.interaction-info {
    display: flex;
    align-items: center;
    gap: 20px;
    font-size: 14px;
    color: #666;
    margin-left: 10px;
}
.icon-item {
    display: flex;
    align-items: center;
    gap: 5px;
    transition: all 0.2s;
}
.liked img {
    filter: brightness(0.8) hue-rotate(180deg); /* 点赞后图标变色 */
}
.blog-title {
    font-size: 18px;
    font-weight: 600;
    color: #1f2937;
    display: block;
}

</style>